package com.lanren.common.utils;

import android.annotation.TargetApi;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.storage.StorageManager;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;

import java.io.File;
import java.lang.reflect.Method;

/**
 * @ClassName FileUtils
 * @Description TODO
 * @Author chongheng.wang
 * @Date 2019/11/3 16:08
 * @Version 1.0
 */
public class FileUtils {

    /**
     * 根据Uri获取文件的绝对路径，解决Android4.4以上版本Uri转换
     *
     * @param fileUri
     */
    @TargetApi(19)
    public static String getPath2uri(Context context, Uri fileUri) {
        LogUtils.d("openFile  uri=" + fileUri.getAuthority());
        LogUtils.d("openFile  uri=" + fileUri.getScheme());
        boolean sdCardExist = false;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //为真则SD卡已装入，
            sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);

        }
        if (context == null || fileUri == null)
            return null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, fileUri)) {
            if (isExternalStorageDocument(fileUri)) {
                String docId = DocumentsContract.getDocumentId(fileUri);
                String[] split = docId.split(":");
                LogUtils.d("openFile isExternalStorageDocument split=" + split[0]);
                if (split[0].equals("primary")) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                } else {
                    if (sdCardExist) {
                        LogUtils.d("openFile isExternalStorageDocument length=" + getAllSdPaths(context).length);
                        if (getAllSdPaths(context).length > 1) {
                            LogUtils.d("openFile isExternalStorageDocument uri=" + getAllSdPaths(context)[1] + " " + sdCardExist);
                            return getAllSdPaths(context)[1] + "/" + split[1];
                        } else {
                            LogUtils.d("openFile isExternalStorageDocument uri=" + getAllSdPaths(context)[0] + " " + sdCardExist);
                            return getAllSdPaths(context)[0] + "/" + split[1];
                        }

                    } else {
                        return Environment.getExternalStorageDirectory() + "/" + split[1];
                    }
                }

            } else if (isDownloadsDocument(fileUri)) {
                String docId = DocumentsContract.getDocumentId(fileUri);
                String[] split = docId.split(":");
                LogUtils.d("openFile isDownloadsDocument uri=" + docId);
                LogUtils.d("openFile isDownloadsDocument uri=" + split[1]);
                LogUtils.d("openFile isDownloadsDocument uri=" + Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS));

                return split[1];


            } else if (isMediaDocument(fileUri)) {
                String docId = DocumentsContract.getDocumentId(fileUri);
                String[] split = docId.split(":");
                String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } // MediaStore (and general)
        else if ("content".equalsIgnoreCase(fileUri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(fileUri)) {
                return fileUri.getLastPathSegment();
            } else if (isTencentUri(fileUri)) {
                File file = new File(fileUri.getPath());
                if (file.getAbsolutePath().indexOf("root_path") > 0) {
                    return file.getAbsolutePath().replace("/root_path/", "/");
                } else {
                    String tencentPath = file.getAbsolutePath().replace("/QQBrowser/", "/");
                    return Environment.getExternalStorageDirectory() + tencentPath;
                }

            }
            return getDataColumn(context, fileUri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(fileUri.getScheme())) {
            return fileUri.getPath();
        }
        return null;
    }

    /**
     * Android4.4 （<19）以下版本获取uri地址方法
     *
     * @param context       上下文
     * @param uri           返回的uri
     * @param selection     条件
     * @param selectionArgs 值
     * @return uri文件所在的路径
     */
    private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String[] projection = {MediaStore.Images.Media.DATA};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return URI权限是否为ExternalStorageProvider
     * Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return URI权限是否为google图片
     * Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    public static boolean isTencentUri(Uri uri) {
        return "com.tencent.mtt.fileprovider".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return URI权限是否为DownloadsProvider.
     * Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return URI权限是否为MediaProvider.
     * Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @return 返回所有路径数组
     */
    public static String[] getAllSdPaths(Context context) {
        Method mMethodGetPaths = null;
        String[] paths = null;
        //通过调用类的实例mStorageManager的getClass()获取StorageManager类对应的Class对象
        //getMethod("getVolumePaths")返回StorageManager类对应的Class对象的getVolumePaths方法，这里不带参数
        StorageManager mStorageManager = (StorageManager) context
                .getSystemService(context.STORAGE_SERVICE);//storage
        try {
            mMethodGetPaths = mStorageManager.getClass().getMethod("getVolumePaths");
            paths = (String[]) mMethodGetPaths.invoke(mStorageManager);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return paths;
    }

    /**
     * 对文件重命名
     *
     * @param filePath 文件的路径
     */
    public static File chageFileName(String filePath, String reName) {
        File file = new File(filePath);
        String oldPath = file.getAbsolutePath();
        String newPath = oldPath.replace(file.getName(), reName);//将文件名替换
        File newFile = new File(newPath);
        if (file.renameTo(newFile)) {
            return newFile;
        }
        return null;
    }

    public static String getPathFileName(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return filePath;
        }

        int filePosi = filePath.lastIndexOf("/");
        return (filePosi == -1) ? filePath : filePath.substring(filePosi + 1);
    }

}
